package beautysalonsystem.controller;

import beautysalonsystem.Util.StpAdminUtil;
import beautysalonsystem.Util.StpCustomerUtil;
import beautysalonsystem.pojo.Admin;
import beautysalonsystem.pojo.Customer;
import beautysalonsystem.result.Result;
import beautysalonsystem.service.UserService;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    //管理员登录
    @PostMapping("/login/admin")
    public Result adminLogin(@RequestBody Admin admin){
        //1.获取管理员手机和密码
        String phone = admin.getPhone();
        String password = admin.getPassword();

        //2.根据手机号获取管理员信息
        Admin adminByPhone = userService.getAdminByPhone(phone);
        if(adminByPhone == null){
            return Result.error("用户名不存在");
        }
        if(!password.equals(adminByPhone.getPassword())){
            return Result.error("密码错误！");
        }
        //3.如果登录成功，让sa-token赋予令牌
        StpAdminUtil.stp.login(phone);
        return Result.success(adminByPhone.getUsername());
    }

    //顾客登录
    @PostMapping("/login/customer")
    public Result customerLogin(@RequestBody Customer customer){
        //1.获取管理员手机和密码
        String phone = customer.getPhone();
        String password = customer.getPassword();

        //2.根据手机号获取管理员信息
        Customer customerByPhone = userService.getCustomerByPhone(phone);
        if(customerByPhone == null){
            return Result.error("用户名不存在");
        }
        if(!password.equals(customerByPhone.getPassword())){
            return Result.error("密码错误！");
        }
        //3.如果登录成功，让sa-token赋予令牌
        StpCustomerUtil.stp.login(phone);
        return Result.success();
    }

    //获取当前管理员信息
    @GetMapping("/admin/detail")
    public Result getAdminDetailByToken(){
        String merchantId = StpAdminUtil.stp.getLoginIdAsString();
        Admin adminByPhone = userService.getAdminByPhone(merchantId);
        return Result.success(adminByPhone);
    }

    //退出登录
    @GetMapping("/logout")
    public Result logout(){
        if (StpCustomerUtil.stp.isLogin()) {
            StpCustomerUtil.stp.logout();
            return Result.success();
        } else if (StpAdminUtil.stp.isLogin()) {
            StpAdminUtil.stp.logout();
            return Result.success();
        } else {
            return Result.error("当前未登录任何身份");
        }
    }
}
